/*
 * HideMe: hide files on a cellphone
 * Copyright (C) 2009  Eduard Martínez
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package hideme;

import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordFilter;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

public class Options {
    private final static String STORE_NAME = "HideMeOptions";
    private final static String DEFAULT_PIN = "";

    public String getPin(){
        String ret = DEFAULT_PIN;
        try {
            RecordStore store = RecordStore.openRecordStore(STORE_NAME, true);
            RecordEnumeration r = store.enumerateRecords(new HeadFilter("PIN"), null, false);
            if(r.hasNextElement()){
                byte[] data = r.nextRecord();
                ret= new String(data, 3, data.length-3);
            }
            store.closeRecordStore();
            //System.out.println("PIN["+ret+"]");
            return ret;
        } catch (RecordStoreException ex) {
            throw new RuntimeException(ex.getMessage());
        }
    }

    public void setPin(String pin){
        try {
            RecordStore store = RecordStore.openRecordStore(STORE_NAME, true);
            RecordEnumeration r = store.enumerateRecords(new HeadFilter("PIN"), null, false);
            byte[] data = ("PIN"+pin).getBytes();
            if(r.hasNextElement()){

                store.setRecord(r.nextRecordId(), data, 0, data.length);
            }else{
                store.addRecord(data, 0, data.length);
            }
            store.closeRecordStore();
        } catch (RecordStoreException ex) {
            throw new RuntimeException(ex.getMessage());
        }
    }

    
    public class HeadFilter implements RecordFilter{
        private final String head;
        public HeadFilter(String head){
            this.head = head;
        }

        public boolean matches(byte[] candidate) {
            return new String(candidate).startsWith(head);
        }
    }
}
